#include <winsock2.h>
#include <iostream>
#include <vector>

#define IPADDRESS "127.0.0.1"
#define PORT 60070

using namespace std;

SOCKET m_socket;

bool socketConnect() {// Initialize Winsock.
    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR)
		printf("Client: Error at WSAStartup().\n");
    else
        printf("Client: WSAStartup() is OK.\n");

	// Create a socket.
    m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (m_socket == INVALID_SOCKET) {
        printf("Client: socket() - Error at socket(): %ld\n", WSAGetLastError());
        WSACleanup();
        return false;
    }
	else
       printf("Client: socket() is OK.\n");

    // Connect to a server.
    sockaddr_in clientService;
    clientService.sin_family = AF_INET;
    // Just test using the localhost, you can try other IP address
    clientService.sin_addr.s_addr = inet_addr("127.0.0.1");
    clientService.sin_port = htons(60070);

    if (connect(m_socket, (SOCKADDR*)&clientService, sizeof(clientService)) == SOCKET_ERROR) {
        printf("Client: connect() - Failed to connect.\n");
        WSACleanup();
        return false;
    }
    else {
       printf("Client: connect() is OK.\n");
       printf("Client: Can start sending and receiving data...\n");
    }

    // Send and receive data.
	printf("Connected\n");
	return true;
}

void envia(char *s, int len) {
	int bytesSent = send(m_socket, s, len, 0);
	if(bytesSent == SOCKET_ERROR)
		printf("Client: send() error %ld.\n", WSAGetLastError());
}

void recebe(char *ans) {
	int bytesRecv = SOCKET_ERROR;
	int pos = 0;
	while (true) {
		recv(m_socket, &ans[pos], 1, 0);
		if (ans[pos] == '\n')
			break;
		pos++;
	}
	ans[pos] = 0;
	//cout << "prolog answered: " << ans << endl;
}

void quit() {
	cout << "Asking prolog to quit" << endl;
	char buff[] = "quit.\n";
	envia(buff, 6);
	char ans[128];
	recebe(ans);
}

char* boardToString(vector< vector<char> > & tab)
{
	char result[2048];
	char aux[4] = "\'x\'";
	result[0]='\0';
	for(int i=0; i < tab.size(); ++i)
	{
		strcat(result,"[");

		for(int j=0; j < tab[i].size(); ++j)
		{
			aux[1] = tab[i][j];
			strcat(result,aux);

			if(j+1 != tab[i].size())
			{
				strcat(result,",");
			}
		}
		if(i+1 != tab.size())
		{
			
			strcat(result,"],");
		}
		else
		{
			strcat(result,"]].");
		}

	}
	return result;
}

void parseBoard(char* result, vector< vector<char> > & tab)
{
	char* pch = strtok(result,"[,.'");
	vector<char> aux;
	while(pch!=NULL)
	{
		if(*pch!=']')
			aux.push_back(*pch);
		else
		{
			tab.push_back(aux);
			aux.clear();
		}
		
		//cout << pch;
		
		pch = strtok (NULL, "[,.'");
	}
}

void getInitialBoard(vector< vector<char> > & tab)
{
	tab.clear();
	char *query = "board(T).\n";
	envia(query, strlen(query));
	char result[2048];
	recebe(result);
	//"explode" do resultado
	parseBoard(result,tab);

}



int main() {
	socketConnect();
	
	vector< vector<char> > tab;
	getInitialBoard ( tab );
	char* t =boardToString(tab);

	quit();
	getchar();
	return 0;
}
